import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, message, Spin, Tooltip } from 'antd';
import { PlayCircleOutlined, CheckCircleOutlined, CloseCircleOutlined, MinusCircleOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { Problem } from '@/types/problem';
import { ContestStatus } from '@/types/contest';
import { problemService } from '@/services/problemService';
import styles from '../Detail.module.css';

interface ContestProblemsProps {
  isAdmin?: boolean;
  isParticipant: boolean;
  contestStatus: ContestStatus;
}

const ContestProblems: React.FC<ContestProblemsProps> = ({ 
  isAdmin = false,
  isParticipant,
  contestStatus
}) => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [problems, setProblems] = useState<Problem[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchProblems();
  }, [id]);

  const fetchProblems = async () => {
    if (!id) return;
    try {
      setLoading(true);
      const response = await problemService.getProblems({ contest_id: Number(id) });
      setProblems(response.data.data.results || []);
    } catch (error) {
      message.error('获取比赛题目失败');
    } finally {
      setLoading(false);
    }
  };

  const handleProblemClick = (problemId: number) => {
    // 如果比赛未开始，不允许进入题目
    if (contestStatus === '1') {
      message.warning('比赛尚未开始，请等待比赛开始后再答题');
      return;
    }
    
    // 管理员可以直接访问题目
    if (!isParticipant && !isAdmin) {
      message.error('您尚未加入该比赛，请先加入比赛');
      return;
    }
    
    // 导航到问题提交页面，并传入contest_id和origin参数
    navigate(`/problem/${problemId}/submit?contest_id=${id}&origin=contest`);
  };

  // 渲染用户题目完成状态
  const renderUserStatus = (userStatus: boolean | null) => {
    if (userStatus === true) {
      return <Tooltip title="已通过"><CheckCircleOutlined style={{ color: '#52c41a', fontSize: '18px' }} /></Tooltip>;
    } else if (userStatus === false) {
      return <Tooltip title="未通过"><CloseCircleOutlined style={{ color: '#f5222d', fontSize: '18px' }} /></Tooltip>;
    } else {
      return <Tooltip title="未尝试"><MinusCircleOutlined style={{ color: '#d9d9d9', fontSize: '18px' }} /></Tooltip>;
    }
  };

  const getProblemColumns = () => {
    return [
      {
        title: '题目ID',
        dataIndex: '_id',
        key: '_id',
      },
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        // 移除标题点击事件，直接显示文本
        render: (text: string) => <span>{text}</span>,
      },
      {
        title: '状态',
        dataIndex: 'user_status',
        key: 'user_status',
        width: 80,
        align: 'center' as const,
        render: (userStatus: boolean | null) => renderUserStatus(userStatus),
      },
      {
        title: '操作',
        key: 'action',
        render: (_: any, record: Problem) => {
          // 比赛未开始时显示锁定状态
          const isContestStarted = contestStatus !== '1';
          
          return (
            <Space size="middle">
              <Button 
                type="primary" 
                icon={isContestStarted ? <PlayCircleOutlined /> : <LockOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  handleProblemClick(record.id);
                }}
                disabled={!isContestStarted}
              >
                {isContestStarted ? '开始答题' : '比赛未开始'}
              </Button>
            </Space>
          );
        },
      },
    ];
  };

  return (
    <div className={styles.problemsSection}>
      {contestStatus === '1' && (
        <div className={styles.notStartedWarning}>
          <LockOutlined style={{ marginRight: '8px' }} />
          比赛尚未开始，题目将在比赛开始后可答题
        </div>
      )}
      <Table 
        columns={getProblemColumns()}
        dataSource={problems}
        loading={loading}
        rowKey="id"
      />
    </div>
  );
};

export default ContestProblems; 